﻿namespace Common
{
    using System;
    using System.Runtime.InteropServices;

    public class Ini
    {
        public static string Read(string filename, string section, string key, string default_value)
        {
            charbuffer charbuffer = new charbuffer();
            Win32_GetString(section, key, default_value, ref charbuffer, 0x100, filename);
            return charbuffer.ToString();
        }

        public static bool ReadBool(string filename, string section, string key, bool default_value)
        {
            try
            {
                return bool.Parse(Read(filename, section, key, default_value ? "true" : "false"));
            }
            catch
            {
                return default_value;
            }
        }

        public static int ReadInt(string filename, string section, string key, int default_value)
        {
            return Win32_GetInt(section, key, default_value, filename);
        }

        [DllImport("kernel32.dll", EntryPoint="GetPrivateProfileIntA")]
        private static extern int Win32_GetInt(string section, string key, int default_value, string filename);
        [DllImport("kernel32.dll", EntryPoint="GetPrivateProfileStringA")]
        private static extern ushort Win32_GetString(string section, string key, string default_value, ref charbuffer return_value, int num_char, string filename);
        [DllImport("kernel32.dll", EntryPoint="WritePrivateProfileStringA")]
        private static extern bool Win32_SetString(string section, string key, string str, string filename);
        public static bool Write(string filename, string section, string key, bool value)
        {
            return Win32_SetString(section, key, value ? "true" : "false", filename);
        }

        public static bool Write(string filename, string section, string key, int value)
        {
            return Win32_SetString(section, key, value.ToString(), filename);
        }

        public static bool Write(string filename, string section, string key, string value)
        {
            return Win32_SetString(section, key, value, filename);
        }
    }
}

